package ru.arriah.servicedesk.web.leadExecutor.action;

import java.io.IOException;
import java.util.Collection;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestPriorityBean;
import ru.arriah.servicedesk.bean.RequestStatusBean;
import ru.arriah.servicedesk.bean.RequestTypeBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;
import ru.arriah.servicedesk.web.commonaction.exception.PrivilegesException;

public class CancelRequestAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;
   protected EmployeeManagerLocalHome employeeManagerLocalHome;
   protected GroupManagerLocalHome groupManagerHome;   
   protected RequestFormErrorBean requestFormErrorBean;

   public CancelRequestAction() throws NamingException {
      super();
      
      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
      
      groupManagerHome =
        Utils.getGroupManagerHomeInterface();
      
      employeeManagerLocalHome =
        Utils.getEmployeeManagerHomeInterface();
   }
   
   
   /**
    * Form validation
    * @param requestBean
    * @param requestManager
    * @return
    */
   private boolean isValid(
     RequestBean requestBean   
   ) {
     boolean valid = true;
     
     requestFormErrorBean = new RequestFormErrorBean();          
     
     if (requestBean.getComment() == null || requestBean.getComment().equals("")) {
       requestFormErrorBean.setComment(
         config.getProperty("ERROR.REQUESTFORM.COMMENT")
       );
       valid = false;
     }     
     
     return valid;
   }

   
   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
       RequestBean requestBean = new RequestBean();                    
       
       int userId = Utils.getUserId(request);                
       int requestId = idVal(request.getParameter("request_id"));              
             
       RequestManagerLocalObject requestManager = 
          requestManagerHome.create();
       
       RequestBean srcRequestBean = 
          requestManager.selectRequest(requestId);
       
       // is curren user owner of the request?
       if (srcRequestBean.getLeadExecutorId() != userId)
          throw new PrivilegesException("invalid userid");
       
       // is request have valid status?
       if (srcRequestBean.getStatusId() != 3)
          throw new Exception("invalid request status");
              
       requestBean.setId(requestId);
       requestBean.setClientText(request.getParameter("text"));
       requestBean.setDispatcherText(request.getParameter("dispatcherText"));                     
       requestBean.setGroupId(idVal(request.getParameter("group_id")));
       requestBean.setRequestTypeId(idVal(request.getParameter("requesttype_id")));                            
       requestBean.setPriority(idVal(request.getParameter("priority")));
       requestBean.setComment(request.getParameter("comment"));                                         
       
       
       if (!isValid(requestBean)) { 
         
         GroupManagerLocalObject groupManager = 
           groupManagerHome.create();        
         
         Collection<GroupBean> groupsList = 
           groupManager.selectGroups();         
         
         Collection<RequestTypeBean> requestTypesList = 
           requestManager.selectRequestTypes();                 
         
         Collection<RequestPriorityBean> priorityList = 
           requestManager.selectPriorityList();                                    
         
         groupManager.remove();
         
         addErrorMessage(
           request,
           config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID")
         );
         
         request.setAttribute("priorityList", priorityList);
         request.setAttribute("requestTypesList", requestTypesList);
         request.setAttribute("groupsList", groupsList);         
         request.setAttribute("requestBean", requestBean);
         request.setAttribute("error", requestFormErrorBean);
         request.setAttribute("action", "requestCommitForm");
         
         return actionMapping.getFailureTarget();
       }                                                                          
       
       if (requestManager.cancelRequestByLeadExecutor(requestBean.getComment(), userId, requestId))
         addInfMessage(
           request,
           config.getProperty("INF.REQUEST_CANCELED")
         );
       else 
         addErrorMessage(
           request,
           config.getProperty("ERROR.REQUEST_NOT_UPDATED")
         );
       
       requestManager.remove();
       
       
       ListRequestsAction listRequestsAction = 
          new ListRequestsAction(requestManagerHome);                   
       listRequestsAction.setConfig(config);
       return listRequestsAction.execute(actionMapping, request, response);
              
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}